package cn.icanci.loopstack.rec.engine.sdk.factor;

import cn.icanci.loopstack.rec.common.aggregation.model.BaseDataDTO;
import cn.icanci.loopstack.rec.common.enums.ResultTypeEnum;
import cn.icanci.loopstack.rec.common.enums.ScriptTypeEnum;
import cn.icanci.loopstack.rec.engine.script.RecScriptEngine;
import cn.icanci.loopstack.rec.engine.script.RecScriptEngineManager;
import cn.icanci.loopstack.rec.engine.script.context.RecScriptEngineContext;
import cn.icanci.loopstack.rec.engine.script.enums.ResultTypeMapEnum;
import cn.icanci.loopstack.rec.engine.sdk.rule.repository.EngineRepositoryHolder;

import javax.annotation.Resource;
import javax.script.Bindings;
import javax.script.CompiledScript;

/**
 * @author icanci
 * @since 1.0 Created in 2022/11/16 22:48
 */
public abstract class AbstractFactor implements Factor {
    /** 推送仓储 */
    @Resource
    protected EngineRepositoryHolder engineRepositoryHolder;

    private final RecScriptEngine    recScriptEngine = RecScriptEngineManager.getRecScriptEngine();

    /**
     * 获取左值
     * 
     * @param bindings bindings
     * @param baseData baseData
     * @return 返回左值
     */
    public String getValue(Bindings bindings, BaseDataDTO baseData) {
        try {
            CompiledScript compiledScript = baseData.getCompiledScript();
            ResultTypeEnum resultType = ResultTypeEnum.valueOf(baseData.getResultType());
            Class<?> classByResultType = ResultTypeMapEnum.getClassByResultType(resultType);
            if (compiledScript == null) {
                RecScriptEngineContext<?> eval = recScriptEngine.eval(ScriptTypeEnum.valueOf(baseData.getScriptType()), bindings, baseData.getScriptContent(), classByResultType);
                return eval.getRealRetVal().toString();
            } else {
                return compiledScript.eval(bindings).toString();
            }
        } catch (Throwable e) {
            return null;
        }
    }
}
